'''
Created on July 1, 2011,

@author: yc30rr1 
'''
from library.executors.TestCase import TestCase
from plugins.FlatFiles.Reader import Reader
import os
from logging import getLogger
from itertools import izip
import string

#Demo Component
from plugins.ProgressBarClass import ProgressBarClass

log = getLogger(__name__)

class CompositeKeyValidation(TestCase):
    '''
    classdocs
    '''
    _fileRows = None
    _fileHasHeader = False
    _step = 1
    _pb = None
#    replacementValue=[]
    validationValue=[]
    fileKeys=[]
    fileValues={}
    replacementValue={}
             
    def __init__(self, testCaseAsDict):
        '''  
        Every class extending (TestCase) class should have this 
        function and should call super class constructor to instantiate base class 
        '''
        super(self.__class__, self).__init__(testCaseAsDict)
             
        
    def executeTestSteps(self):
        try:
            self.getInputFileAsList()
            # For Visual Progress
            totalRows = len(self._fileRows)
            self._pb = ProgressBarClass(totalRows)
            i = 0
            # For Visual Progress
            
            if totalRows>0:
                for i in range(i,totalRows,self._step):
                    
                    self._pb.progress(i+1)
    
                    self.validateMulitipleColumn(self._fileRows[i])
                    
                self.testCaseResults()
                
            else:
                #print "File has no records hence corresponding test case not executed"
                return
        except Exception as e:
            self.testCaseFailedOnce()
            self.testCaseResults()
            log.debug("Exception in CompositeKeyValidation ",+e)
            log.debug("Exception occured" + str(self.tcid))
            
    def validateMulitipleColumn(self, row):
        
#        del self.replacementValue
        
        del self.validationValue[:]
        del self.fileKeys[:]
        
        try:
            attrName=self.getTestCaseOption('ATTR_NAME')
            primaryCol = self.getTestCaseOption("PRIMARY_COLUMN").split(',')
            validateCol = self.getTestCaseOption("VALIDATE_COLUMN").split(',')
            dbName = self.getTestCaseOption('DATABASE')
            dbQuery = self.getTestCaseOption('QUERY').strip()
                        
            replacementValue = None
            if self._fileHasHeader==False:
                self.replacementValue=self.convertToDictionaries(row, primaryCol)
                self.fileValues=self.convertToDictionaries(row, validateCol)
            #End if
            if self._fileHasHeader==True:
                for i in range(len(primaryCol)):
                    self.replacementValue.append(row[str(primaryCol[i])])
                for j in range(len(validateCol)):
                    self.validationValue.append(row[str(validateCol[j])])
                #End For
            #End If
            for key in self.replacementValue.keys():
                if self.replacementValue[key]==attrName:
                    #query="select case  when gxs.site_attribute_name in ('MASTER_SET_SHOW','SKAVA','DEFAULT_CATEGORY','SHIPPING_STATE_EXCLUSION','SHIPPING_METHOD_EXCLUSION','BULLET_LINK','REBATE_LINK','DISCLAIMERS','BULLET_TEXT','SHIPPING_BULLET_TEXT','WEDDING_BULLET_TEXT') then 'M'  else 'U'  end as \"UNARY/MULTI\",  case  when gxs.site_searchable_ind=0 then 'N' else 'Y'  end as \"ATTR_ACT_VIEW\", case  when (R.no_registry_flag='') or (R.no_registry_flag is null) then 'D'  else 'U'  end as \"STATUS\",  case  when (R.no_registry_flag='') or (R.no_registry_flag is null) then 'NULL'  else R.no_registry_flag end as \"NOT_FOR_WC_REGISTRY\" from gxs_attribute_type_def gxs , product P inner join registry R on R.product_id=P.product_id  where gxs.site_attribute_name in ('NOT_FOR_WC_REGISTRY') and P.product_id in (19770)"
                    #query="select case WHEN gxs.repeating_ind=0 THEN 'U' ELSE 'M'end as \"UNARY/MULTI\" ,case WHEN gxs.site_searchable_ind= 0 THEN 'N' ELSE 'Y' end as \"SITE_STATUS\", case when (US.size_name ='') or (US.size_name is null)  THEN 'D' else 'U' end as \"STATUS\" , case  when (US.size_name ='') or (US.size_name is null) THEN 'NULL' else US.size_name end as \"SSIZE\" from gxs_attribute_type_def gxs , upc inner join upc_size US on upc.size_id=US.size_id where gxs.site_attribute_name in ('SIZE') and upc.upc_id in (1297077)"
                    query = self.multipleReplace(dbQuery,self.replacementValue)
                    queryResult = self.runSingleRowQuery(query, dbName)
                    if queryResult!= None:
                        for v1,v2 in zip(sorted(self.fileValues.items()),sorted(queryResult.items())):
                            if (v1!=v2)and(v2=='NULL'):
                                    self.addTestExecutionNotes('primaryKey=' + str(self.replacementValue['xxxx']) + ', dbValue=' +str(v2) + ', FileValue=' +str(v1))
                                    self.testCaseFailedOnce()
                            else:
                                pass
                    else:
                        self.addTestExecutionNotes('primaryKey=' + str(self.replacementValue['xxxx']) + ', dbValue=' +str(queryResult) )
                        self.testCaseFailedOnce()
                else:
                    return

        except :
            self.testCaseFailedOnce()
            log.critical("Unable to Validate Single Row : " + str(row))

    @staticmethod
    def supportedExecutionTypes(tcTypes):
        '''  
        Every class extending (TestCase) class should have this function 
        The Automation script will read  
        '''
        return tcTypes in ["CompositeKeyValidation", "Compositekeyvalidaion", "MultipleColumnValidation"]
    
    def getInputFileAsList(self):
#        print "Executing TestCase ::  " + str(self.tcid)
        csvObj = Reader(self.testCase['FULL_FILE_NAME'])
        self._fileRows = csvObj.processToListWithDictCols()
        if len(self._fileRows)>0:
            print "Executing TestCase ::  " + str(self.tcid)
        else:
            print "NO records found in "+str(self.testCase['FULL_FILE_NAME'] + " hence corresponding test case not executed")
            
        self._fileHasHeader = csvObj.hasHeader()
        self._fileHasHeader=False
        
    def convertToDictionaries(self,row,convertValues):
        values=[]
        keys=[]
        dictValues={}
        j=0
        for i in range(len(convertValues)):
            values.append(row['COLUMN-' + str(convertValues[i][j])])
            keys.append(convertValues[i][j+2:len(convertValues[i])+1].lower())
        dictValues=dict(zip(keys,values))
        return dictValues

    

    

    
        
